package it.unibz.easytravel.tracker;



import it.unibz.easytravel.db.LocationDbAdapter;
import it.unibz.easytravel.travel.EditTravel;
import it.unibz.easytravel.R;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

public class TrackerService extends Service implements LocationListener {

	private final static String TAG = "TRACKER_SERVICE_TAG";
	private static int travel_id;

	LocationManager locationManager;
	Location currentLocation;	
	NotificationManager mNM;

	private LocationDbAdapter mLocationDb;

	public void onLocationChanged(Location loc) {
		Log.d(TAG, loc.toString());
		if (loc!=null) {
			mLocationDb = new LocationDbAdapter(this);
			mLocationDb.open();
			mLocationDb.createCoordinate(travel_id, loc);
			mLocationDb.close();
		}
	}

	@Override
	public void onCreate() {
		SharedPreferences settings = getSharedPreferences(EditTravel.PREFS_NAME, 0);
		travel_id = settings.getInt(EditTravel.TRAVEL_ID, -1);

		mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		subscribeToLocationUpdates();	 
		showNotification();
	}

	public void onDestroy() {
		mNM.cancel(R.string.remote_service_started);
		unsubscribeFromLocationUpdates();				
	}

	private void unsubscribeFromLocationUpdates() {
		this.locationManager.removeUpdates(this);		
	}

	public void onProviderDisabled(String provider) {}
	public void onProviderEnabled(String provider) {}
	public void onStatusChanged(String provider, int status, Bundle extras) {}

	public void subscribeToLocationUpdates() {
		this.locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
	}

	private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {};

	@Override
	public IBinder onBind(Intent intent) {		
		if (IRemoteService.class.getName().equals(intent.getAction())) {
			return mBinder;
		}
		return null;
	}

	private void showNotification() {

		CharSequence text = getText(R.string.remote_service_started);


		Notification notification = new Notification(R.drawable.icon, text,
				System.currentTimeMillis());


		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				new Intent(this, Tracker.class), 0);


		notification.setLatestEventInfo(this, getText(R.string.remote_service_label),
				text, contentIntent);

		mNM.notify(R.string.remote_service_started, notification);
	}
}
